<template>
    <div class="favor-form-dialog">
        <el-dialog v-model="dialogFormVisible"
                   :title="opt === 'EDIT' ? '修改' : '添加'"
                   :close-on-click-modal="false"
                   :close-on-press-escape="false"
                   @close="$emit('update:show', false)"
                   destroy-on-close
                   top="8vh">
            <el-form :model="favorForm" :rules="favorFormRules" ref="favorForm" label-position="right"
                     label-width="100px">
                <input :name="favorForm.id" type="hidden"/>
                <input type="hidden" :name="favorForm.logo"/>
                <el-form-item label="资源名称" prop="name">
                    <el-input v-model="favorForm.name" placeholder="请输入资源名称"/>
                </el-form-item>
                <el-form-item label="资源 URL" prop="url">
                    <el-input v-model="favorForm.url" placeholder="请输入资源 URL"/>
                </el-form-item>
                <el-form-item label="所属类别" prop="catalogId">
                    <el-cascader v-model="favorForm.catalogId"
                                 placeholder="请选择资源类别"
                                 :options="catalogData"
                                 :props="catalogProps"/>
                </el-form-item>
                <el-form-item label="资源 logo" prop="logo">
                    <el-upload v-loading="uploadLoading"
                               class="logo-uploader"
                               action="/favorite-api/image/upload"
                               :show-file-list="false"
                               :on-success="handleLogoSuccess"
                               :on-error="handleLogoFail"
                               :before-upload="beforeLogoUpload">
                        <template #slot>
                            <div class="el-upload__tip"
                                 style="display: inline; padding-left: 15px">只能上传jpg/png文件，且不超过2MB
                            </div>
                        </template>
                        <img v-if="favorLogoUrl" :src="favorLogoUrl" class="favor-logo"/>
                        <i v-else class="el-icon-plus logo-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="资源简介" prop="description">
                    <el-input type="textarea"
                              :autosize="{ minRows: 2, maxRows: 4 }"
                              v-model="favorForm.description"
                              placeholder="请输入资源简介"/>
                </el-form-item>
            </el-form>
            <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" plain @click="submitFavorForm('favorForm')">提 交</el-button>
                <el-button type="info" plain @click="dialogFormVisible = false">关 闭</el-button>
            </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import favoriteReq from "@/services/favorite/request";

export default {
    name: "FavoriteForm",
    props: {
        show: {
            type: Boolean,
            default: false,
        },
        opt: {
            type: String,
        },
        datas: {
            type: Object,
        },
    },
    watch: {
        show() {
            if (this.show) {
                this.getAllCatalog()
                this.favorForm = this.datas
                this.dialogFormVisible = this.show
                if (this.opt === "EDIT") {
                    this.favorLogoUrl = "/favorite-api" + this.datas.logo
                } else {
                    this.favorLogoUrl = null
                }
            }
        },
    },
    data() {
        return {
            formLabelWidth: "100px",
            dialogFormVisible: false,

            favorForm: {},
            favorFormRules: {
                name: [{required: true, message: "请输入资源名称", trigger: "blur"}],
                url: [{required: true, message: "请输入资源 URL", trigger: "blur"}],
                catalogId: [
                    {required: true, message: "请选择资源类别", trigger: "blur"},
                ],
                description: [
                    {required: true, message: "请填写资源简介", trigger: "blur"},
                ],
            },

            catalogData: [],
            catalogProps: {
                value: "id",
                label: "name",
                expandTrigger: "hover",
                children: "children",
                emitPath: false,
            },

            favorLogoUrl: "",
            uploadLoading: false,
        };
    },
    methods: {
        async getAllCatalog() {
            // 获取列表
            let r = await favoriteReq.getAllCatalog()
            if (r.code === 0) {
                this.catalogData = r.data;
            } else {
                this.$message.error('资源列表加载失败， 请刷新！');
            }
        },
        submitFavorForm(formName) {
            this.$refs[formName].validate(async (valid) => {
                if (valid) {
                    // 提交后台
                    let r = await favoriteReq.save(this.favorForm)
                    if (r.code === 0) {
                        this.$message.success("操作成功")
                        this.dialogFormVisible = false
                        // 让父组件刷新列表
                        this.$emit("finishMethod")
                    } else {
                        this.$message.error(r.msg)
                    }
                } else {
                    return false;
                }
            });
        },
        showLogo(path) {
            let _this = this;
            this.$axios
                .get("/favorite-api/image/view-base64?path=" + path)
                .then(function (r) {
                    if (r.code === 0) {
                        _this.favorLogoUrl = r.data;
                    } else {
                        _this.$message.error("图片显示失败！");
                    }
                });
        },
        handleLogoSuccess(res, file) {
            this.uploadLoading = false;
            if (res.code === 0) {
                this.$message.success("上传成功！");
                this.favorForm.logo = res.data;
                this.favorLogoUrl = URL.createObjectURL(file.raw);
            } else {
                this.$message.error("上传失败：" + res.msg);
            }
        },
        handleLogoFail() {
            this.uploadLoading = false;
        },
        beforeLogoUpload(file) {
            const isJPG = file.type === "image/jpeg";
            const isPNG = file.type === "image/png";
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG && !isPNG) {
                this.$message.error("图片只能是【JPG、PNG】格式!");
                return false;
            }
            if (!isLt2M) {
                this.$message.error("图片大小不能超过 2MB!");
                return false;
            }
            this.uploadLoading = true;
            return true;
        },
    },
};
</script>

<style lang="scss">
.favor-form-dialog .el-dialog__body {
    padding: 10px 20px 0;
}

.logo-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.logo-uploader .el-upload:hover {
    border-color: #409eff;
}

.logo-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 90px;
    height: 90px;
    line-height: 90px;
    text-align: center;
}

.favor-logo {
    width: 90px;
    height: 90px;
    display: block;
}
</style>